package ar.com.photo_admin.activity;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import ar.com.photo_admin.Constants;
import ar.com.photo_admin.ImageShareCommand;
import ar.com.photo_admin.R;
import ar.com.photo_admin.domain.Album;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

public class PhotoPagerActivity extends Activity {

	private Album album;
	
	private DisplayImageOptions options;

	private ImageLoader imageLoader = ImageLoader.getInstance();
	
	private ViewPager pager;

	private boolean instanceStateSaved;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.photo_pager);
		
		Integer pagerPosition = null;
		
		if (savedInstanceState != null) {
			album = (Album) savedInstanceState.getSerializable(Constants.ALBUM);
			pagerPosition = savedInstanceState.getInt(Constants.PHOTO_POSITION);
			
		} else {
			Bundle extras = getIntent().getExtras();
			
			album = (Album) extras.getSerializable(Constants.ALBUM);
			pagerPosition = extras.getInt(Constants.PHOTO_POSITION);
		}
		
		setTitle(album.getName());

		options = new DisplayImageOptions.Builder()
			.showImageForEmptyUri(R.drawable.ic_empty)
			.resetViewBeforeLoading()
			.cacheOnDisc()
			.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
			.bitmapConfig(Bitmap.Config.RGB_565)
			.displayer(new FadeInBitmapDisplayer(300))
			.build();

		pager = (ViewPager) findViewById(R.id.pager);
		pager.setAdapter(new PhotoPagerAdapter());
		pager.setCurrentItem(pagerPosition);
	}
	
	private class PhotoPagerAdapter extends PagerAdapter {

		private LayoutInflater inflater;

		public PhotoPagerAdapter() {
			inflater = getLayoutInflater();
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			View rootView = (View) object;
			
			/*ImageView imageView = (ImageView) rootView.findViewById(R.id.image);
			
			BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
			
			if (drawable != null) {
				Bitmap bitmap = drawable.getBitmap();
				if (bitmap != null) {
					bitmap.recycle();
				}
			}*/

			((ViewPager) container).removeView(rootView);
		}

		@Override
		public void finishUpdate(View container) {
		}

		@Override
		public int getCount() {
			return album.getPhotos().size();
		}

		@Override
		public Object instantiateItem(ViewGroup view, int position) {
			final View imageLayout = inflater.inflate(R.layout.item_pager_image, view, false);
			final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
			final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);

			final String url = album.getPhotos().get(position).getUrl();
			
			imageLoader.displayImage(url, imageView, options, new SimpleImageLoadingListener() {
				
				@Override
				public void onLoadingStarted() {
					spinner.setVisibility(View.VISIBLE);
				}

				@Override
				public void onLoadingFailed(FailReason failReason) {
					String message = null;
					
					switch (failReason) {
						case IO_ERROR:
							message = getString(R.string.connection_problem);
							break;
						case OUT_OF_MEMORY:
							message = getString(R.string.out_of_memory_error);
							break;
						case UNKNOWN:
							message = getString(R.string.unknown_error);
							break;
					}
					Toast.makeText(PhotoPagerActivity.this, message, Toast.LENGTH_LONG).show();

					spinner.setVisibility(View.GONE);
					imageView.setImageResource(R.drawable.ic_error);
				}

				@Override
				public void onLoadingComplete(Bitmap loadedImage) {
					spinner.setVisibility(View.GONE);
				}
			});

			((ViewPager) view).addView(imageLayout, 0);
			return imageLayout;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view.equals(object);
		}

		@Override
		public void restoreState(Parcelable state, ClassLoader loader) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View container) {
		}
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		
		instanceStateSaved = true;
		outState.putSerializable(Constants.ALBUM, album);
		outState.putLong(Constants.PHOTO_POSITION, pager.getCurrentItem());
	}

	@Override
	protected void onDestroy() {
		if (!instanceStateSaved) {
			imageLoader.stop();
		}
		super.onDestroy();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = this.getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.share) {
			final String url = album.getPhotos().get(pager.getCurrentItem()).getUrl();
			new ImageShareCommand().share(this, url);
		}
		
		return true;
	}	
}
